package com.merry.sb.aop.jdk;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JdkDynamicProxyExample {

    interface Service {
        void execute();
    }

    static class ServiceImpl implements Service {
        @Override
        public void execute() {
            System.out.println("Service method executed");
        }
    }

    static class ServiceLogHandler implements InvocationHandler {
        private final Object target;

        ServiceLogHandler(Object target) {
            this.target = target;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("Before method execution");
            Object result = method.invoke(target, args);
            System.out.println("After method execution");
            return result;
        }
    }

    /**
     * JDK的动态代理使用Proxy完成。
     * @param args
     */
    public static void main(String[] args) {
        Service service = new ServiceImpl();
        Service proxyService = (Service) Proxy.newProxyInstance(
                ServiceImpl.class.getClassLoader(),
                new Class[]{Service.class},
                new ServiceLogHandler(service));
        proxyService.execute();
    }
}
